package com.java.digitalsignagesystem.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.digitalsignagesystem.entity.UserLogin;
import com.java.digitalsignagesystem.utils.JwtUtil;
import com.java.digitalsignagesystem.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisUtil redisUtil;
    private static final String OPTIONS="OPTIONS";


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST,DELETE,PUT");
        res.addHeader("Access-Control-Allow-Headers", "*");
        res.addHeader("Access-Control-Max-Age", "3600");

        // 如果是OPTIONS则结束请求
        if (OPTIONS.equals(((HttpServletRequest) request).getMethod())) {
            response.getWriter().println("ok");
            return ;
        }
        String token=request.getHeader("zhzp-token");
        if(!ObjectUtils.isEmpty(token))
        {
            Claims claims=null;
            try {
                claims = JwtUtil.parseJWT(token);
            } catch (Exception e) {
                //response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setStatus(200);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                ObjectMapper mapper = new ObjectMapper();
                String errorMessage = "token验证失败: " + e.getMessage();
                HashMap<String, Object> map = new HashMap<>();
                map.put("error", errorMessage);
                String jsonResponse = mapper.writeValueAsString(map);
                response.getWriter().print(jsonResponse);
                return ;
                //throw new RuntimeException(e+"token验证失败");
            }
            String userId = claims.getSubject();
            UserLogin loginUser =  redisUtil.getCacheObject("login"+userId);
            log.debug(String.valueOf(loginUser));
            if(ObjectUtils.isEmpty(loginUser)){
                response.setStatus(200);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                ObjectMapper mapper = new ObjectMapper();
                String errorMessage = "用户未登录";
                HashMap<String, Object> map = new HashMap<>();
                map.put("error", errorMessage);
                String jsonResponse = mapper.writeValueAsString(map);
                response.getWriter().print(jsonResponse);
                return ;
            }
            UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request,response);
    }
}
